# -*- coding:utf-8 -*-
from redis.commands.search.result import Result
from aioredis import Redis as AsyncRedis

from ..search import SearchableModel


class AsyncSearchableModel(SearchableModel):
    @classmethod
    async def async_search(
        cls,
        query: str,
        **kwargs
    ) -> Result:
        """异步执行搜索"""
        redis_conn = await cls._get_async_redis_connection()
        return await redis_conn.ft(cls.__name__).search(query, **kwargs)

    @classmethod
    async def _get_async_redis_connection(cls) -> AsyncRedis:
        if not hasattr(cls, "__redis_conn__") or cls.__redis_conn__ is None:
            raise ConnectionError(
                f"模型 {cls.__name__} 未配置 Redis 连接，请先调用 {cls.__name__}.set_redis_connection()"
            )
        return cls.__redis_conn__

    @classmethod
    async def async_search_and_parse(cls, query: str, **kwargs):
        result = await cls.async_search(query, **kwargs)
        return [cls(**data) for data in result.docs]